import os
import helpers.FileHelper as FileHelper



class LuaModule:

    def __init__(self, merger, name, path):
        self.name = name
        lines = FileHelper.r_line(path)
        rows = len(lines)
        row_s = -1
        for i in range(rows):
            query = self.parse_require_line(lines[i])
            if query is not None:
                merger.load_module(query)
                row_s = i
        self.return_line = None
        row_e = rows
        for i in range(rows - 1, -1, -1):
            if self.is_return_line(lines[i]):
                row_e = i
                self.return_line = lines[i]
        self.lines = lines[row_s + 1:row_e]

    def __str__(self):
        return self.name

    def export(self, output):
        output.extend(self.lines)

    @staticmethod
    def parse_require_line(line):
        line = line.replace(" ", "")
        si = line.find('''require("''')
        ei = line.rfind('''")''')
        if 0 < si < ei:
            return line[si + 9: ei]
        return None

    @staticmethod
    def is_return_line(line):
        return line.startswith("return ")



class LuaMerger:

    def __init__(self, root_path, entry_path):
        self.root = root_path
        self.module_tree = {}
        self.module_list = []
        self.entry = self.load_module(entry_path)

    def load_module(self, query):
        mod_root = self.module_tree
        mod_path = query.split("/")
        for i in range(len(mod_path) - 1):
            mod_name = query[i]
            mod_root = mod_root.setdefault(mod_name, {})
        mod_name = mod_path[-1]
        if mod_name in mod_root:
            return mod_root[mod_name]
        mod = LuaModule(self, query, FileHelper.solve_path(self.root, query+".lua"))
        mod_root[mod_name] = mod
        self.module_list.append(mod)
        return mod

    def export(self):
        lines = []
        for module in self.module_list:
            lines.append("\n\n\n\n\n---------- {}.lua ----------\n".format(module.name))
            lines.extend(module.lines)
        mod_last = self.module_list[-1]
        if mod_last.return_line is not None:
            lines.append(mod_last.return_line)
        return "".join(lines)



def merge(root_path, entry_path, output_path):
    if not os.path.exists(os.path.join(root_path, entry_path+".lua")):
        return False
    merger = LuaMerger(root_path, entry_path)
    output_path = FileHelper.solve_path(root_path, output_path)
    print("Merging to", output_path)
    FileHelper.w_data(merger.export(), output_path)
    return True

